<?php

namespace app\models\system;

use basic\BaseModel;
use think\facade\Db;
use traits\ModelTrait;

/**
 * 门店管理
 * Class SystemStore
 * @package app\models\system
 */
class SystemStore extends BaseModel
{

    use ModelTrait;

    /**
     * 主键的ID
     * @var string
     */
    protected $pk = "id";

    /**
     * 模型的名称
     * @var string
     */
    protected $name = 'system_store';

    /**
     * 获取所有的门店列表
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList()
    {
        return self::where("wxapp_id", self::$wxapp_id)
            ->where("is_del", 0)
            ->order("id DESC")
            ->select()->each(function ($item, $key){
                // 获取门店的机器的数量
                $device_list = Db::name("store_device")
                    ->where('store_id', $item['id'])
                    ->field('id, device_name, device_no, car_order_id')
                    ->where('is_del', 0)
                    ->select()->each(function ($item, $key){
                        if ($item['car_order_id']) {
                            $item['is_free'] = false;
                        } else {
                            $item['is_free'] = true;
                        }
                        return $item;
                    });
                $item['device_list'] = $device_list;
                $count = count($device_list);
                $flag = Db::name("store_device")
                    ->where('store_id', $item['id'])
                    ->where('is_del', 0)
                    ->where('car_order_id', 0)
                    ->count();
                if ($item['is_work'] == 0) {
                    $item['free'] = 3;
                } elseif ($count == $flag) {
                    $item['free'] = 1;
                } else {
                    $item['free'] = 2;
                }
                return $item;
            });
    }
}